;(function(){
    function MapGis(id,pram,callback){
        var _this=this;
        _this._id=id;
        _this._fun=callback||Function; 
        //地图中心点
        _this._centerPoint='';            
        _this._config={
            //绘制折线的样式
            styleoption:{
                strokeColor:"red",    //边线颜色。
                fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
                strokeWeight: 1,       //边线的宽度，以像素为单位。
                strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
                fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
                strokeStyle: 'solid' //边线的样式，solid或dashed。
            },
            //是否开启工具栏
            toolShow:true,
            //工具栏是新建还是重置
            btnContent:"新建",
            showMapTool:false,
            centerposition:'四川',
        }
        //默认label样式
        _this.styleLabe={
            color : "#555",
            fontSize : "12px",
            height : "20px",
            lineHeight : "20px",
            fontFamily:"微软雅黑"
        };
        _this._map={};
        _this._mask=null;
        //保存可修改的点
        _this._editorPoint={},
        //绘制折线点坐标
        _this._drawPoint=[];
        _this.getConfig(pram.styleoption,_this._config.styleoption);
        pram.styleoption= _this._config.styleoption;
        _this.getConfig(pram,_this._config);
        _this._styleOpion=_this._config.styleoption;
        _this.init();
        
    };
    MapGis.prototype={
        //地图初始化
        init:function(){
            var _this=this;
            _this._map = new BMap.Map(_this._id);
            _this._centerPoint =  new BMap.Point(109.717426,19.27341);
        //    if(_this.showMapTool){
        //         _this._map.addControl(new BMap.MapTypeControl({type:BMAP_MAPTYPE_CONTROL_DROPDOWN}));
        //         _this._map.disable3DBuilding();
        //    }
        //     if(_this._config.centerposition){
        //        // debugger;
        //          _this._map.centerAndZoom(_this._config.centerposition,12);
        //     }
        _this._map.centerAndZoom(_this._centerPoint,12);
            //根据浏览器定位
            // var geolocation = new BMap.Geolocation();
            // geolocation.getCurrentPosition(function(r){
            //    // alert(123);
            //     _this._map.centerAndZoom(r.point,12);

            // },{enableHighAccuracy: true})
            _this._map.enableScrollWheelZoom();
            _this._map.disableDoubleClickZoom()
            _this._map.setMapStyleV2({
                styleId: '208b2f2481097bf8676bb6145e4fd97d'
            });
            _this._fun(_this);
            if(!_this._config.toolShow) return false;
            _this.createTools();


        },
        //检测配置信息styleOpion
        getConfig:function(obj,obj2){
            var _this=this;
            if(obj&&obj!=''){
                $.extend(obj2, obj2,obj);
            }else{
                return false;
            }
        },
        //创建控制按钮
        createTools:function(){
            var _this=this;
            var _html='<div class="createTools" id="'+_this._id+'tools">';
                _html+='<label class="gis-reset git-btn"><span></span>'+_this._config.btnContent+'</label><label class="gis-cancel git-btn"><span></span>取消</label><label class="gis-save git-btn"><span></span>保存</label>'
                _html+='</div>'; 
            $("#"+_this._id).append(_html); 
            //绑定按钮功能
            $("#"+_this._id+"tools label span").click(function(event){
                event.stopPropagation()
            })
            var buttons=$("#"+_this._id+"tools label");
            buttons.each(function(i){                        
                $(this).click(function(){
                    if(i==0){
                        _this.createMask();
                        _this.clearoverlays();
                        _this.drawPolyline();
                        $("#"+_this._id+"tools .gis-save span").show();
                    }
                    if(i==1){
                       // _this.moveMask();
                      // allOverlay = _this._map.getOverlays();
                       _this.clearoverlays();
                       _this.drawOneGird();
                       $("#"+_this._id+"tools .gis-save span").show();
                    }
                    if(i==2){
                        if(JSON.stringify(_this._editorPoint)=='{}'){                                                        
                            _this._fun({
                                id:null,
                                point:_this._drawPoint
                            });
                        }else{
                            _this._fun({
                                id:_this._editorPoint.id,
                                point:_this._drawPoint,
                            });
                        }
                       

                    }
                    buttons.removeClass("active");
                    $(this).addClass("active");
                });
            });
        },
        //创建遮罩
        createMask:function(){
            var _this=this;
            _this.moveMask();
            var mask  = document.createElement("div");
            var size = this._map.getSize();
            mask.style.cssText = "z-index:9999;position:absolute;background:rgba(255,255,0,0);cursor:crosshair;width:" + size.width + "px;height:" + size.height + "px";
            _this._mask=_this._map.getPanes().floatPane.appendChild(mask);
            console.log(_this._styleOpion);
            //console.log(_this._mask,"_this._mask");
            //mmm=_this._mask;
            //绑定鼠标移动遮罩位置重置
            _this._mask.onmousemove=function(e){
                _this.resetMaskPosition();
            }
        },
        //移除遮罩
        moveMask:function(){
            var _this=this;
            if(_this._mask&&_this._mask.parentNode){
                _this._mask.parentNode.removeChild(_this._mask);
            }                
        },
        //地图移动时候重置遮罩的位置
        resetMaskPosition:function(){
            var _this=this;
            var point = _this._map.pixelToPoint(new BMap.Pixel(0, 0));                    
            console.log(point,"point");
            var pixel = _this._map.pointToOverlayPixel(point);
            //console.log(point,"jfasjdfkajsdfljk",new BMap.Pixel(0, 0),pixel);
            _this._mask.style.left = pixel.x + "px";
            _this._mask.style.top  = pixel.y + "px"; 
        },
        //绘制折线
        drawPolyline:function(){
            var _this=this;
            var points=[];
            var drawPoint=[];
            var isBinded=false;
            var overlay;
            _this._map.addEventListener("mousedown",drawPolylineStart);
            //开始绘制折线
            function drawPolylineStart(e){
                isBinded=true;
                if( e.button == 1 || e.button==0) return ;
                points.push(e.point);
                drawPoint = points.concat(points[points.length - 1]);
                if (points.length == 1) {
                    overlay = new BMap.Polyline(drawPoint,_this._styleOpion);
                    _this._map.addOverlay(overlay);
                } else {
                    overlay.setPath(drawPoint);
                }
                if (isBinded) {
                   // console.log(isBinded,"isBinded02");
                    _this._map.addEventListener('mousemove',drawPolylineIng);
                    _this._map.addEventListener('dblclick',drawPolylineEnd);
                    var _string=[]
                    for(var i=0;i<points.length;i++){
                        _string+=points[i].lng+','+points[i].lat+"|";
                    };
                    console.log(points,'1111',_string);
                }


            }
            //绘制折线
            function drawPolylineIng(e){
                if (!isBinded) return; 
                overlay.setPositionAt(drawPoint.length - 1, e.point);
            }
            //双击折线绘制结束并生成几何图形
            function drawPolylineEnd(e){
                isBinded = false;
                points.push(e.point);
                overlay.setPath(points);
                _this.clearoverlays();
                overlay = new BMap.Polygon(drawPoint,_this._styleOpion);                
                _this._drawPoint=drawPoint;
                _this._map.addOverlay(overlay);
                _this._map.removeEventListener('mousedown',drawPolylineStart);
                _this._map.removeEventListener('mousemove',drawPolylineIng);
                _this._map.removeEventListener('dblclick',drawPolylineEnd);               
                $("#"+_this._id+"tools button").removeClass("active");
                $("#"+_this._id+"tools button span").hide();
               // debugger;
               // _this._mask.parentNode;
               // _this._mask.parentNode.removeChild(_this._mask)
                _this.moveMask();
               // console.log(isBinded,"isBinded");
            }
        },
        //清除覆盖物
        clearoverlays:function(){
            var _this=this;
            _this._map.clearOverlays();
        },
        //清除所有的覆盖物
        clearalloverlays:function(){
            var _this=this;
            allOverlay = _this._map.getOverlays();
            for(var i in allOverlay){
                allOverlay[i].enableMassClear();
            }
            _this.clearoverlays();
        },
        //绘制网格(多点)
        drawGird:function(obj,callback,callback02){
            var lookdetail=lookdetail||Function
            var fun=callback||Function;
            var fun2=callback02||Function;
            var _this=this;
            var overlay=[];
            var textover=[];
            var _pointcenter=[];
            //创建信息窗口对象
            var opts = {
				width :100,     // 信息窗口宽度
				height:60,     // 信息窗口高度
				title : "" , // 信息窗口标题
				enableMessage:true//设置允许信息窗发送短息
			   };
            if(!obj||obj.length==0) return false;
            for(var i=0;len=obj.length,i<len;i++){
                var styleObj=obj[i].styleOption||{}
                overlay[i] = new BMap.Polygon(obj[i].position,getStyle(_this._styleOpion,styleObj));
                _this._map.addOverlay(overlay[i]);
                overlay[i].addEventListener("click",function(i){
                    return function(){
                        fun(i);
                    }
                }(i));
                overlay[i].addEventListener("dblclick",function(i){
                    return function(){
                        fun2(i);
                    }
                }(i));
                overlay[i].disableMassClear()
                if(textover[i]){
                    textover[i].disableMassClear()
                }
            }
            function addClickHandler(content,marker){
                   // alert(123);
                marker.addEventListener("click",function(e){
                        openInfo(content,e)

                    }
                );


            }
            function openInfo(content,e){
                var p = e.target;
                var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
                var infoWindow = new BMap.InfoWindow(content,opts);  // 创建信息窗口对象
                _this._map.openInfoWindow(infoWindow,point); //开启信息窗口
            }
            //debugger;
            //获取网格样式
            function getStyle(obj1,obj2){
                return $.extend({}, obj1, obj2);
            }
            
        },
        //添加ico
        addIco:function(obj){
            var _this=this;
            console.log(obj,"dddd");
            _this.clearoverlays();
            if(obj.length==0) return false;
            icons=[];
            icons["normal_unit"]="zcshdw.png";
            icons["abnormal_unit"]="xhdw.png";
            icons["normal_fire_facility"]="zcgzxf.png";
            icons["abnormal_fire_facility"]="gzxf.png";
            icons["key_unit_station"]="shwxxfz.png";
            icons["community_station"]="shwxxfz.png";
            //console.log(icons,"iconsdd");
            var pt = _this._centerPoint;
            var _position=[];
            for(var i=0;i<obj.length;i++){
            //var pt=new BMap.Point(obj[i].lng, obj[i].lat);
               // console.log(test,"test");
                // 将标注添加到地图中
                if(obj[i].lng||obj[i].lat){
                    _position.push({
                        lng:obj[i].lng,
                        lat: obj[i].lat
                    })
                }
                _this._map.addOverlay(new BMap.Marker(new BMap.Point(obj[i].lng, obj[i].lat),{icon:new BMap.Icon("/static/js/gridMap/images/"+icons[obj[i].ico], new BMap.Size(50,50))})); 
            } 
           // debugger 
           // _position;
           var wz=_this.getAreaCenter(_position)
           debugger;
           _this._map.centerAndZoom(new BMap.Point(wz.lng,wz.lat),10);
           
            //_this._map.centerAndZoom(_this.getAreaCenter(_position),12);       
        },
        //重新绘制可编辑网格(单点)
        drawOneGird:function(){
            var _this=this;
            if(_this._editorPoint){
                var  overlay = new BMap.Polygon(_this._editorPoint.point,_this._styleOpion);
                _this._map.addOverlay(overlay);
            }
            
        },
        //计算区域的中心点
         getAreaCenter: function(lnglatarr){  
              //var path = e.;//Array<Point> 返回多边型的点数组
                //var ret=parseFloat(num1)+parseFloat(num2);  
                var x = 0.0;
                var y = 0.0;
                var lngarr=[];
                var latarr=[];
                 for(var i=0;i<lnglatarr.length;i++){
                     lngarr.push(lnglatarr[i].lng); 
                     latarr.push(lnglatarr[i].lat);        
                 }
                 var lngMax=Math.max.apply(null,lngarr);
                 var lngMin=Math.min.apply(null,lngarr);
                 var latMax=Math.max.apply(null,latarr);
                 var latMin=Math.min.apply(null,latarr);
                 //console.log(lngMax,lngMaxflag,lngMinflag,latMaxflag,latMinflag,"经纬度");
                 x=(lngMax+lngMin)/2;
                 y=(latMax+latMin)/2;

                // for(var i=0;i<lnglatarr.length;i++){
                //     x=x+ parseFloat(lnglatarr[i].lng);
                //     y=y+ parseFloat(lnglatarr[i].lat);
                // }
                // x=x/lnglatarr.length;
                // y=y/lnglatarr.length;
                //console.log(x,y,"dddddddddddddddddd");
                
                //return new BMap.Point(path[0].lng,path[0].lat);
                // return new BMap.Point(x,y);
                //return path[0];
                return {
                    lng:x,
                    lat:y
                }  
            // debugger;                
            // var total = lnglatarr.length;
            // var X=0,Y=0,Z=0;
            // $.each(lnglatarr, function(index, lnglat) {
            //     var lng = lnglat.lng * Math.PI / 180;
            //     var lat = lnglat.lat * Math.PI / 180;
            //     var x,y,z;
            //     x = Math.cos(lat) * Math.cos(lng);
            //     y = Math.cos(lat) * Math.sin(lng);
            //     z = Math.sin(lat);
            //     X += x;
            //     Y += y;
            //     Z += z;
            // });

            // X = X/total;
            // Y = Y/total;
            // Z = Z/total;

            // var Lng = Math.atan2(Y,X);
            // var Hyp = Math.sqrt(X*X + Y*Y);
            // var Lat = Math.atan2(Z,Hyp);
            // return {
            //     lng:Lng*180/Math.PI,
            //     lat:Lat*180/Math.PI
            // }
        },
        //绘制单个位置
        getBoundary:function(name,callback){
            var _this=this;
            var fun=callback||Function;
            var bdary = new BMap.Boundary();
            bdary.get(name, function(rs){       //获取行政区域
                _this.clearoverlays();;        //清除地图覆盖物
                var count = rs.boundaries.length; //行政区域的点有多少个
                if (count === 0) {
                    alert('未能获取当前输入行政区域');
                    return ;
                }
                var pointArray = [];
                for (var i = 0; i < count; i++) {
                    var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor:_this._config.styleoption.strokeColor,fillColor: 'rgba(255,255,255,.1)'}); //建立多边形覆盖物
                    _this._map.addOverlay(ply);  //添加覆盖物
                    pointArray = pointArray.concat(ply.getPath());
                }
                _this._map.setViewport(pointArray);    //调整视野
                // var local = new BMap.LocalSearch(_this._map, {
                //     renderOptions:{map: _this._map}
                // });
                // local.search("街子古镇");
                fun();
            });
        }
    
    },
    //创建图标ico
    
    //注册到window上
    window.mapGis=function(id,pram,callback){
        return new MapGis(id,pram,callback);
    }
})();